package com.wjm.demo.test1.net_test.tcp_socket_test.uploadpic_thread;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class UploadTask implements Runnable {
    private Socket accept;

    public UploadTask(Socket accept) {
        this.accept = accept;
    }

    @Override
    public void run() {
        try {
            int count = 0;
            String ip = accept.getInetAddress().getHostAddress();
            System.out.println(ip + ".......connected");
            InputStream is = accept.getInputStream();
            File fileDir = new File("d:\\server");
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            File file = new File(fileDir, ip + "微信截图_20180707211416.png");
            if (file.exists()) {
                count++;
                file = new File(fileDir, ip + "微信截图_20180707211416(" + count + ").png");
            }
            FileOutputStream fos = new FileOutputStream(file);

            byte[] buf = new byte[1024];
            int len;
            while ((len = is.read(buf)) != -1) {
                fos.write(buf, 0, len);
            }
            OutputStream out = accept.getOutputStream();

            out.write("上传成功".getBytes());

            fos.close();

            accept.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
